package top.archiesean.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.archiesean.handler.RpcServerHandler;

/**
 * @author ArchieSean
 * @description netty启动类
 * @date 2024-03-06
 */
@Component
public class RpcServer implements DisposableBean {

    /**
     * 主线程组
     */
    private EventLoopGroup bossGroup;
    /**
     * 工作线程组
     */
    private EventLoopGroup workerGroup;

    @Autowired
    private RpcServerHandler rpcServerHandler;

    public void startServer(String ip, int port) throws InterruptedException {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new StringEncoder());
                        // todo 业务处理
                        pipeline.addLast(rpcServerHandler);
                    }
                });
        ChannelFuture future = bootstrap.bind(ip, port).sync();
        System.out.println("--netty服务端启动成功--");
        future.channel().closeFuture().sync();
    }

    /**
     * 该方法，在容器销毁时调用
     *
     * @throws Exception ex
     */
    @Override
    public void destroy() throws Exception {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
